<?php

namespace app\common\model;

use think\Model;

class Favorite extends Model
{
    // 表名
    protected $name = 'favorite';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'type_text',
        'create_time_text',
        'status_text',
        'update_time_text'
    ];
    
	const TYPE_GOODS = 1;
	const TYPE_BUS = 2;
	
	//收藏类型
	public static $_type = [
		self::TYPE_GOODS => '商品',
		self::TYPE_BUS => '商家'
	];
    
    public function getTypeList()
    {
    	return self::$_type;
    }

    
    const STATUS_Y = 1;
    const STATUS_C = 0;
    
    //收藏状态
    public static $_status = [
        self::STATUS_Y => '收藏中',
	    self::STATUS_C => '已取消'
    ];
    
    public function getStatusList()
    {
    	return self::$_status;
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	public function user(){
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods(){
		return $this->belongsTo('goods', 'relation_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function business(){
		return $this->belongsTo('business', 'relation_id', 'id', '', 'left')->setEagerlyType(0);
	}
	/**
	 * 添加收藏
	 * @param $userId 用户ID
	 * @param $type 收藏类型
	 * @param $id 收藏ID
	 * @return false|int
	 */
	public function addRecord($userId, $type, $id) {
    	$data = [
    		'user_id' => $userId,
		    'type' => $type,
		    'relation_id' => $id,
	    ];
    	
    	$res = $this->isUpdate(false)->save($data);
    	return $res;
	}
}
